﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Strom.Core.Characters
{
    [Serializable]
    public class Character
    {
        public string Name { get; set; }
        public CharacterStats Stats { get; set; }
        public CharacterGraphics Graphics { get; set; }
        public string OwnerAccountLogin { get; set; }

        public Character(string name, CharacterStats stats, CharacterGraphics graphics, string ownerLogin)
        {
            Name = name;
            Stats = stats;
            Graphics = graphics;
            OwnerAccountLogin = ownerLogin;
        }

        public byte[] Serialize()
        {
            var stream = new MemoryStream();

            using (var writer = new BinaryWriter(stream))
            {
                //Global infos
                writer.Write(Name);
                writer.Write(OwnerAccountLogin);
                //Stats
                writer.Write(Stats.Level);
                writer.Write(Stats.HP);
                writer.Write(Stats.MP);
                //Graphics
                writer.Write(Graphics.SpriteID);
                byte[] array = new byte[2 + stream.Length];
                Array.Copy(BitConverter.GetBytes((short)stream.Length), array, 2);
                Array.Copy(stream.ToArray(), 0, array, 2, stream.Length);

                return array;
            }
        }

        public static Character Deserialize(byte[] datas)
        {
            Character character;
            using(var reader = new BinaryReader(new MemoryStream(datas)))
            {
                //Global infos
                string name = reader.ReadString();
                string owner = reader.ReadString();
                //Stats
                int level = reader.ReadInt32();
                int hp = reader.ReadInt32();
                int mp = reader.ReadInt32();
                //Graphics
                int spriteId = reader.ReadInt32();

                character = new Character(name, new CharacterStats(level, hp, mp), new CharacterGraphics(), owner);
            }
            return character;
        }
    }
}
